package com.bdqn.kind;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisAPI {

    private static JedisPool jedisPool;

    static {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(50);
        config.setMaxIdle(10);
        config.setMaxIdle(7);
        config.setMaxWaitMillis(1000);
        config.setTestOnBorrow(true);

        jedisPool = new JedisPool(
                config,
                "192.168.159.128",
                6379,
                10000,
                "123456",
                0
        );
    }

    /**
     *
     */
    public void destroy(){
        if (!(jedisPool == null) || jedisPool.isClosed()){
            jedisPool.close();
        }
    }

    /**
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key,String value) {
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.set(key, value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }

    public String get(String key){
        String value = null;
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            value = jedis.get(key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return value;
    }

    public static void main(String[] args) {
        String addr = "192.168.159.128";
        String port ="6397";
        Jedis jedis = new Jedis(addr,Integer.parseInt(port));
        System.out.println(jedis.get("haha"));
    }
}
